package com.gjh.controller.system;

import com.github.pagehelper.PageInfo;
import com.gjh.controller.BeanController;
import com.gjh.domain.system.Dept;
import com.gjh.service.system.DeptService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/system/dept")
public class DeptController extends BeanController{

    @Autowired
    private DeptService deptService;

    @RequestMapping(value = "/list",name = "显示部门列表数据")
    public String findAll(@RequestParam(name ="page",defaultValue = "1")int pageNum,@RequestParam(name = "pageSize",defaultValue = "10")int pageSize){
//        List<Dept> deptList = deptService.findAll();
//        request.setAttribute("list",deptList);
        PageInfo page= deptService.findByPage(getCompanyId(),pageNum,pageSize);
        request.setAttribute("page",page);
        return "/system/dept/dept-list";
    }

    @RequestMapping(value = "/toAdd" ,name = "进入新增部门界面")
    public String toAdd(){
        //需要回显所有该企业所用部门的名称
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);
        return "/system/dept/dept-add";
    }

    @RequestMapping(value = "/edit",name = "保存部门数据")
    public String edit(Dept dept){
        if(StringUtils.isEmpty(dept.getId())){
            dept.setId(UUID.randomUUID().toString());//设置企业id
            dept.setCompanyId(getCompanyId());
            dept.setCompanyName(getComanyName());
            if(dept.getParent().getId()==null||dept.getParent().getId().equals("")) {
//            String id = new Date().toString();
                dept.getParent().setId(null);
            }
            deptService.save(dept);
        }else{
            if(dept.getParent().getId()==null||dept.getParent().getId().equals("")) {
//            String id = new Date().toString();
                dept.getParent().setId(null);
            }
            deptService.update(dept);
        }
        return "redirect:/system/dept/list.do";
    }

    @RequestMapping(value = "/toUpdate",name = "进入部门更新界面")
    public String toUpdate(String id){
        Dept dept=deptService.findById(id);
        request.setAttribute("dept",dept);
        //查询本企业的所有部门
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);
        return "system/dept/dept-update";
    }

    @RequestMapping(value = "/delete",name = "删除部门")
    public String deleteById(String id){
        deptService.deleteById(id);
        return "redirect:/system/dept/list.do";
    }


}
